<?php

namespace app\manystore\Logic\Pay;

use app\manystore\model\PayLog;
use app\manystore\Model\ManystoreOrderRecord;
use app\manystore\Model\ManystoreShop;
use app\manystore\Model\ManystoreConfig;

class PayLogic
{
    /**
     * 支付方式
     * @return array[]
     */
    public function payTypeMap(){
        return [
            1 => ['type' => 1, 'name' => '微信支付','code' => 'wechat'],
            2 => ['type' => 2, 'name' => '支付宝','code' => 'alipay'],
            3 => ['type' => 3, 'name' => '银联支付','code' => '']
        ];
    }

    /**
     * 插入订单主表
     * @param $data
     * @return int|string
     */
    public function createOrder($data){
        //订单总表待插入数据
        $pay_data = [
            'shop_id' => $data['shop_id'] ?? 0,
            'controller' => $data['controller'] ?? '',
            'order_id' => $data['order_id'] ?? 0,
            'order_sn'=> $data['out_trade_no'] ?? '',
            'user_id' => $data['user_id'] ?? 0,
            'price' => $data['price'] ?? 0,
            'coupon_id' => $data['coupon_id'] ?? 0,
            'coupon_amount' => $data['coupon_amount'] ?? 0,
            'discount' => $data['discount'] ?? 0,
            'activity_id' => $data['activity_id'] ?? 0,
            'activity_price' => $data['activity_price'] ?? 0,
            'score' => $data['score'] ?? 0,
            'score_amount' => $data['score_amount'] ?? 0,
            'real_price' => $data['real_price'] ?? 0,
            'pay_amount' => $data['pay_amount'] ?? 0,
            'transaction_id' => $data['transaction_id'] ?? '',
            'payment_json' => $data['payment_json'] ?? '',
            'pay_type'=> $data['pay_type'] ?? 0,
            'pay_time'=> $data['pay_time'] ?? 0,
            'status'=> $data['status'] ?? 0,
            // 'refund_status'=> $data['refund_status'] ?? 0,
            // 'refund_amount'=> $data['refund_amount'] ?? 0,
            'createtime' => time()
        ];

        //插入主订单表
        return PayLog::insertGetId($pay_data);
    }

    /**
     * 支付成功，用于支付成功回调用
     * @param $params
     * @return bool
     * @throws DataNotFoundException
     * @throws DbException
     * @throws Exception
     * @throws ModelNotFoundException
     */
    public function payment($params)
    {
        // 加锁获取订单信息
        $orderInfo = ManystoreOrderRecord::where('sn', $params['out_trade_no'])
            ->lock(true)
            ->find();
        $orderInfo = objToArray($orderInfo) ?? [];


        if (empty($orderInfo)) {
            return false;
        }
        if (!empty($orderInfo['pay_time'])) {
            // return false;
        }
        // TODO: 支付回调过来，如果是关闭了的订单，钱要原路退还，不能继续支付流程

        // 修改支付单信息
        $updateInfo = [
            'status' => 1,
            'pay_time' => time(),
            'pay_amount' => $params['pay_money'] ?? 0
        ];

        ManystoreOrderRecord::where('sn', $params['out_trade_no'])->update($updateInfo);

        //查询主订单ID
        $payLogInfo = PayLog::where('controller',$params['controller'])
            ->where('order_id',$orderInfo['id'])
            ->where('shop_id',$orderInfo['shop_id'])
            // ->field('id')
            ->find();
        $payLogInfo = objToArray($payLogInfo) ?? [];
        if(!empty($payLogInfo)){

            $store_info = ManystoreShop::get($orderInfo['shop_id']);
            if(!empty($store_info))
            {
                //服务时间延长
                if($orderInfo['type'] == 1 && $store_info['end_time'] < $orderInfo['end_time'])
                {
                    $update = ['end_time' => $orderInfo['end_time'],'is_open' => 1];

                    if(empty($store_info['star_time']))
                    {
                        $update['star_time'] = $orderInfo['star_time'];
                    }
                    ManystoreShop::where('id',$orderInfo['shop_id'])->update($update);
                }
                //直播余数增加
                else if($orderInfo['type'] == 2 && $orderInfo['num'] > 0)
                {
                    $new_live_day = bcadd($store_info['live_day'],$orderInfo['num']);
                    ManystoreShop::where('id',$orderInfo['shop_id'])->update(['live_day' => $new_live_day]);
                }
                //短信余数增加
                else if($orderInfo['type'] == 3 && $orderInfo['num'] > 0)
                {
                    $new_sms_num = bcadd($store_info['sms_num'],$orderInfo['num']);
                    ManystoreShop::where('id',$orderInfo['shop_id'])->update(['sms_num' => $new_sms_num]);
                }
                //营销余数增加
                else if($orderInfo['type'] == 4 && $orderInfo['num'] > 0)
                {
                    $new_market_day = bcadd($store_info['market_day'],$orderInfo['num']);
                    ManystoreShop::where('id',$orderInfo['shop_id'])->update(['market_day' => $new_market_day]);
                }
            }

            //todo 额外数据，用于保存交易单号等信息，由于不知道回调返回的参数，因此这边暂时为空
            $expandData = [
                'transaction_id' => ''
            ];
            //执行主订单回调
            $this->payLogNotify($payLogInfo['id'],$expandData);
        }

        return true;
    }

    /**
     * 主订单回调
     * @param $orderId
     * @param null $expandData
     * @return false
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function payLogNotify($orderId,$expandData = null){
        // 加锁获取订单信息
        $orderInfo = PayLog::where('id', $orderId)
            ->lock(true)
            ->find();
        $orderInfo = objToArray($orderInfo) ?? [];
        if (empty($orderInfo)) {
            return false;
        }
        if (!empty($orderInfo['pay_time'])) {
            return false;
        }

        // 修改支付单信息
        $updateInfo = [
            'status' => 1,
            'pay_time' => time()
        ];
        $updateInfo = array_merge($expandData,$updateInfo);

        PayLog::where('id', $orderId)->update($updateInfo);

        return true;
    }
}
